package com.xywang.servlet.user;

import com.xywang.pojo.User;
import com.xywang.service.user.UserService;
import com.xywang.service.user.UserServiceImpl;
import com.xywang.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ServletLogin extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("进入LoginServlet.....");
        // 获取用户名密码
        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");
        // 和数据库中的密码进行对比，调用业务层
        UserService userService = new UserServiceImpl();
        // login方法中调用getLoginUser(Connection ,userCode)方法，调用BaseDao.execute方法，
        // 将一行数据封装为一个用户取出
        User user = userService.login(userCode, userPassword);

        if(user != null){ // loginUser存在，则说明用户密码正确，可以登录
            // 将用户的所有信息放到session中
            req.getSession().setAttribute(Constants.USER_SESSION,user);
            System.out.println("用户："+user.getUserName()+" 登录成功！");
            // 跳转主页
            resp.sendRedirect(req.getContextPath()+"/jsp/frame.jsp");

        }else{// 查无此人，登录失败
            // 转发回登录页面，顺带提示它，用户名或者密码错误；
            req.setAttribute("error","用户名或者密码错误！");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }
    }
}
